package org.jeecg.modules.demo.puInvoice.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.advancesReceived.entity.YxAdvancesReceived;
import org.jeecg.modules.demo.advancesReceived.mapper.YxAdvancesReceivedMapper;
import org.jeecg.modules.demo.puInvoice.entity.PuInvoice;
import org.jeecg.modules.demo.puInvoice.mapper.PuInvoiceMapper;
import org.jeecg.modules.demo.puInvoice.service.IPuInvoiceService;
import org.jeecg.modules.demo.pubuyorder.entity.PuBuyOrder;
import org.jeecg.modules.demo.pubuyorder.mapper.PuBuyOrderMapper;
import org.jeecg.modules.demo.pusettlement.entity.PuSettlement;
import org.jeecg.modules.demo.pusettlement.mapper.PuSettlementMapper;
import org.jeecg.modules.demo.soOrderDetail.entity.SoOrderDetail;
import org.jeecg.modules.demo.soOrderDetail.entity.WarehouseOrderVo;
import org.jeecg.modules.demo.soOrderDetail.mapper.SoOrderDetailMapper;
import org.jeecg.modules.demo.soOrderDetail.mapper.WarehouseOrderVoMapper;
import org.jeecg.modules.demo.sopayorder.entity.SoPayorder;
import org.jeecg.modules.demo.sopayorder.mapper.SoPayorderMapper;
import org.jeecg.modules.demo.utils.BigDecimalUtil;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.jeecg.modules.demo.warehouseorder.entity.WarehouseOrder;
import org.jeecg.modules.demo.warehouseorder.mapper.WarehouseOrderMapper;
import org.jeecg.modules.demo.yxadjust.mapper.YxAdjustMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: pu_invoice
 * @Author: jeecg-boot
 * @Date: 2021-12-16
 * @Version: V1.0
 */
@Service
public class PuInvoiceServiceImpl extends ServiceImpl<PuInvoiceMapper, PuInvoice> implements IPuInvoiceService {
    @Resource
    private PuInvoiceMapper puInvoiceMapper;
    @Resource
    private PuBuyOrderMapper puBuyOrderMapper;
    @Resource
    private YxAdvancesReceivedMapper yxAdvancesReceivedMapper;
    @Resource
    private PuSettlementMapper puSettlementMapper;
    @Resource
    private YxAdjustMapper yxAdjustMapper;
    @Resource
    private WarehouseOrderMapper warehouseOrderMapper;
    //采购成本
    @Resource
    private SoOrderDetailMapper soOrderDetailMapper;
    @Resource
    private SoPayorderMapper soPayorderMapper;
    @Resource
    private WarehouseOrderVoMapper warehouseOrderVoMapper;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    private static final String TITLE = "单据审核";


    private String getMessage(String name,String date) {
        String str ="由【"+name+"】于【"+date+"】发起的采购发票单需要您的审核，请及时查看！";
        return str;
    }

    @Override
    public Map<String,Double> getYFData(String str){
        return puInvoiceMapper.getYFData(str);
    }

    @Override
    public String getMaxCode() {
        return puInvoiceMapper.getMaxCode();
    }

    @Override
    public PuInvoice getByNumber(String number) {
        return puInvoiceMapper.getByNumber(number);
    }

    @Override
    public List<String> selectByPusNo(String pusNo) {
        return puInvoiceMapper.selectByPusNo(pusNo);
    }

    @Override
    public Page<PuInvoice> getList(Page<PuInvoice> page, PuInvoice puInvoice) {
        return page.setRecords(puInvoiceMapper.getList(page, puInvoice));
    }

    @Override
    public Map<String, BigDecimal> getNumByOrderAndLX(String str) {
        return puInvoiceMapper.getNumByOrderAndLX(str);
    }

    @Override
    public List<PuInvoice> getDataByNumber(String str) {
        return puInvoiceMapper.getDataByNumber(str);
    }

    @Override
    public List<PuInvoice> getByPoOrder(String str) {
        return puInvoiceMapper.getByPoOrder(str);
    }

    //采购成本
    @Override
    public List<PuInvoice> getBywoNo(String woNo) {
        return puInvoiceMapper.getBywoNo(woNo);
    }


    @Override
    public List<PuInvoice> getPaymentJob(String parameter) {
        return puInvoiceMapper.getPaymentJob(parameter);
    }
    @Override
    public String  getDepartId() {
        return puInvoiceMapper.getDepartId();
    }

    @Override
    public List<PuInvoice> getYkpByPoOrder(String poOrder) {
        return puInvoiceMapper.getYkpByPoOrder(poOrder);
    }

    @Override
    @Transactional
    public boolean checkInvoice(PuInvoice puInvoice){
        try{
            puInvoice.setShenhe(1);
            puInvoice.setShTime(new Date());
            PuSettlement puSettlement = puSettlementMapper.getByPusNo(puInvoice.getPusNo());
            puSettlement.setShenhe(1);
            puSettlementMapper.updateById(puSettlement);
            puInvoiceMapper.updateById(puInvoice);
            if(Integer.parseInt(puInvoice.getFplx())!=4){
                String[] woNos = puInvoice.getWoNo().split(",");
                if(woNos.length > 1){
                    for(int i = 0;i<woNos.length;i++){
                        WarehouseOrder  warehouseOrder = warehouseOrderMapper.getByWoNo(woNos[i]);
                        warehouseOrder.setFpsl(new BigDecimal(BigDecimalUtil.add(warehouseOrder.getFpsl().doubleValue(),puInvoice.getFpsl().doubleValue())));
                        warehouseOrder.setFpje(new BigDecimal(BigDecimalUtil.add(warehouseOrder.getFpje().doubleValue(),puInvoice.getWsje().doubleValue())));
                        warehouseOrder.setZgsl(new BigDecimal(BigDecimalUtil.sub(warehouseOrder.getZgsl().doubleValue(),warehouseOrder.getFpsl().doubleValue())));
                        Double cb = BigDecimalUtil.mul(warehouseOrder.getWsdj().doubleValue(),warehouseOrder.getZgsl().doubleValue());
                        warehouseOrder.setZxcb(new BigDecimal(BigDecimalUtil.add(cb,warehouseOrder.getFpje().doubleValue())));
                        warehouseOrderMapper.updateById(warehouseOrder);
                    }
                }else{
                    WarehouseOrder  warehouseOrder = warehouseOrderMapper.getByWoNo(puInvoice.getWoNo());
                    warehouseOrder.setFpsl(new BigDecimal(BigDecimalUtil.add(warehouseOrder.getFpsl().doubleValue(),puInvoice.getFpsl().doubleValue())));
                    warehouseOrder.setFpje(new BigDecimal(BigDecimalUtil.add(warehouseOrder.getFpje().doubleValue(),puInvoice.getWsje().doubleValue())));
                    warehouseOrder.setZgsl(new BigDecimal(BigDecimalUtil.sub(warehouseOrder.getZgsl().doubleValue(),warehouseOrder.getFpsl().doubleValue())));
                    Double cb = BigDecimalUtil.mul(warehouseOrder.getWsdj().doubleValue(),warehouseOrder.getZgsl().doubleValue());
                    warehouseOrder.setZxcb(new BigDecimal(BigDecimalUtil.add(cb,warehouseOrder.getFpje().doubleValue())));
                    warehouseOrderMapper.updateById(warehouseOrder);
                }

            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }
    @Override
    @Transactional
    public boolean unCheckInvoice(PuInvoice puInvoice){
        try{
            if(Integer.parseInt(puInvoice.getFplx())==4) {
                PuSettlement puSettlement = puSettlementMapper.getByPusNo(puInvoice.getPusNo());
                puSettlement.setShenhe(0);
                puSettlement.setShTime(null);
                puSettlementMapper.updateById(puSettlement);
            }
            puInvoice.setShenhe(0);
            puInvoice.setCreateTime(null);
            WarehouseOrder  warehouseOrder = warehouseOrderMapper.getByWoNo(puInvoice.getWoNo());
            //判断如果没有入库单的情况
            if(warehouseOrder != null){
                warehouseOrder.setFpsl(new BigDecimal(BigDecimalUtil.sub(warehouseOrder.getFpsl().doubleValue(),puInvoice.getFpsl().doubleValue())));
                warehouseOrder.setFpje(new BigDecimal(BigDecimalUtil.sub(warehouseOrder.getFpje().doubleValue(),puInvoice.getWsje().doubleValue())));
                warehouseOrder.setZgsl(new BigDecimal(BigDecimalUtil.add(warehouseOrder.getZgsl().doubleValue(),warehouseOrder.getFpsl().doubleValue())));
                Double cb = BigDecimalUtil.mul(warehouseOrder.getWsdj().doubleValue(),warehouseOrder.getZgsl().doubleValue());
                warehouseOrder.setZxcb(new BigDecimal(BigDecimalUtil.add(cb,warehouseOrder.getFpje().doubleValue())));
                warehouseOrderMapper.updateById(warehouseOrder);
            }
            puInvoiceMapper.updateById(puInvoice);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }



    private YxAdvancesReceived updateAdvancesReceived(PuInvoice puInvoice) throws Exception {
        YxAdvancesReceived advancesReceived = yxAdvancesReceivedMapper.getByReceiptNumber(puInvoice.getReceiptNumber());
        Double sup = advancesReceived.getSupAmount().doubleValue();
        Double amount = puInvoice.getYfuseje().doubleValue();
        Double supamount = BigDecimalUtil.sub(sup, amount);
        advancesReceived.setSupAmount(supamount <= 0?new BigDecimal(0):new BigDecimal(supamount));
        return advancesReceived;

    }

    private SoPayorder getSoPayOrder(PuInvoice puInvoice,String precode) {
        String str = soPayorderMapper.getMaxCode();
        Map<String, String> map = new HashMap<>();
        map.put("maxCode",str==null?null:str);
        String name = precode+"FK_";
        String resultCode = generateOddUtil.createCode(map, name);
        SoPayorder soPayorder = new SoPayorder();
        soPayorder.setShanchu(0);
        soPayorder.setShenhe(1);
        soPayorder.setBusType(2);
        soPayorder.setReceiptNumber(puInvoice.getReceiptNumber());
        soPayorder.setSopNo(resultCode);
        soPayorder.setPuiNo(puInvoice.getPuiNo());
        soPayorder.setSopDate(new Date());
        soPayorder.setSopAmount(puInvoice.getHsje());
        soPayorder.setSfamount(puInvoice.getYfuseje());
        soPayorder.setPoStaff(puInvoice.getPoStaff());
        soPayorder.setDepartment(puInvoice.getDepartment());
        soPayorder.setSaleman(puInvoice.getSaleman());
        soPayorder.setJsfs(2);
        soPayorder.setPoOrder(puInvoice.getPoOrder());
        soPayorder.setTradecode(puInvoice.getTradecode()!=null?puInvoice.getTradecode():null);
        soPayorder.setFkjine(soPayorder.getSfamount());
        return soPayorder;
    }

    private PuSettlement getSettlement(PuInvoice puInvoice,String precode) {
        PuSettlement puSettlement = new PuSettlement();
        String str = puSettlementMapper.getMaxCode();
        Map<String, String> map = new HashMap<>();
        map.put("maxCode",str==null?null:str);
        String name = precode+"JS_";
        String resultCode = generateOddUtil.createCode(map, name);
        puSettlement.setPusNo(resultCode);
        puSettlement.setQoQuantity(puInvoice.getFpsl());
        puSettlement.setHsdj(puInvoice.getHsdj());
        puSettlement.setHsje(puInvoice.getHsje());
        puSettlement.setWsdj(puInvoice.getWsdj());
        puSettlement.setWsje(puInvoice.getWsje());
        puSettlement.setPsTax(puInvoice.getPsTax());
        puSettlement.setShenhe(0);
        puSettlement.setShanchu(0);
        puSettlement.setDjlx(1);
        puSettlement.setFpsl(puInvoice.getFpsl());
        puSettlement.setPoOrder(puInvoice.getPoOrder());
        puSettlement.setPayTotail(puInvoice.getFpsl());
        puSettlement.setRealityTotail(puInvoice.getFpsl());
        puSettlement.setKtotail(new BigDecimal(0.00000));
        puSettlement.setDtotail(new BigDecimal(0.00000));
        puSettlement.setPoTotail(puInvoice.getPoTotail());
        puSettlement.setIsInvoice(1);
        puSettlement.setPoStaff(puInvoice.getPoStaff());
        puSettlement.setCreateTime(new Date());
        puSettlement.setPusCdate(new Date());
        puSettlement.setYhxTotail(puInvoice.getFpsl());
        puSettlement.setYhxMoney(puInvoice.getHsje());
        puSettlement.setDepartment(puInvoice.getDepartment());
        puSettlement.setChumdwmc(puInvoice.getChumdwmc());
        puSettlement.setSaleman(puInvoice.getSaleman());
        puSettlement.setTradecode(puInvoice.getTradecode()!=null?puInvoice.getTradecode():null);
        return puSettlement;
    }


    @Override
    @Transactional
    public boolean addInvoice(PuInvoice puInvoice,String precode) {
        try {
            if (puInvoice.getReceiptNumber() != null) {
                puInvoice.setYjjine(new BigDecimal(BigDecimalUtil.sub(puInvoice.getHsje().doubleValue(), puInvoice.getYfuseje().doubleValue())));
                puInvoice.setSupamount(puInvoice.getYfuseje());
                YxAdvancesReceived advancesReceived= updateAdvancesReceived(puInvoice);
                yxAdvancesReceivedMapper.updateById(advancesReceived);
                puInvoice.setYfsyje(new BigDecimal(BigDecimalUtil.sub(puInvoice.getYfsyje().doubleValue(), puInvoice.getYfuseje().doubleValue())));
                SoPayorder soPayorder = getSoPayOrder(puInvoice,precode);
                soPayorderMapper.insert(soPayorder);
            } else {
                puInvoice.setSupamount(new BigDecimal(0.000));
            }
            PuBuyOrder puBuyOrder = puBuyOrderMapper.getByNumber(puInvoice.getPoOrder());
            puBuyOrder.setInvoice(1);
            puBuyOrder.setYkje(new BigDecimal(BigDecimalUtil.add(puInvoice.getHsje().doubleValue(), puBuyOrder.getYkje().doubleValue())));
            puBuyOrder.setYktotal(new BigDecimal(BigDecimalUtil.add(puInvoice.getFpsl().doubleValue(), puBuyOrder.getYktotal().doubleValue())));
            puBuyOrder.setYhxTotail(new BigDecimal(BigDecimalUtil.add(puInvoice.getFpsl().doubleValue(), puBuyOrder.getYhxTotail().doubleValue())));
            puBuyOrder.setYhxMoney(new BigDecimal(BigDecimalUtil.add(puInvoice.getHsje().doubleValue(), puBuyOrder.getYhxMoney().doubleValue())));
            puBuyOrderMapper.updateById(puBuyOrder);
            puInvoice.setQoQuantity(new BigDecimal(0.000));
            puInvoice.setYfhx(4);
            List<PuSettlement> settlements = puSettlementMapper.getByPoOrder(puInvoice.getPoOrder());
            if (!settlements.isEmpty()) {
                for (PuSettlement settlement : settlements) {
                    settlement.setYkTotal(puInvoice.getYkTotal());
                    settlement.setYkje(puInvoice.getYkje());
                    puSettlementMapper.updateById(settlement);
                }
            }
            PuSettlement settlement = getSettlement(puInvoice,precode);
            puSettlementMapper.insert(settlement);
            puInvoice.setXsFpsl(puInvoice.getFpsl());
            puInvoice.setPusNo(settlement.getPusNo());
            puInvoice.setTradecode(puBuyOrder.getTradecode()!=null?puBuyOrder.getTradecode():null);
            puInvoice.setFplx("4");
            puInvoiceMapper.insert(puInvoice);


            //采购成本
            List<WarehouseOrder> rkList = warehouseOrderMapper.getBypoNo(puInvoice.getPoOrder());//根据采购订单号查询所有入库单
            getChengBen(rkList);

            LoginUser user = sysBaseAPI.getUserById(puInvoice.getPoStaff());
            TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
            templateMessageDTO.setFromUser("管理员");
            templateMessageDTO.setToUser(puInvoice.getSaleman()+",");
            templateMessageDTO.setTitle(TITLE);
            templateMessageDTO.setTemplateCode("order");
            Map<String, String> templateParam = new HashMap<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date= simpleDateFormat.format(new Date());
            templateParam.put("ts_date",date);
            templateParam.put("ts_content", getMessage(user!=null?user.getRealname():"业务员不存在！", date));
            templateParam.put("checkOrder",puInvoice.getPuiNo());
            templateParam.put("cd_url","/puinvoice/puInvoice/list");
            templateMessageDTO.setTemplateParam(templateParam);
            sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }

    }

    @Override
    @Transactional
    public boolean addSettlementInvoice(PuInvoice puInvoice,String precode) {
        try {
            String str = puInvoice.getPusNo();

            PuSettlement puSettlement = puSettlementMapper.getByPusNo(str);
            puSettlement.setKtotail(new BigDecimal(BigDecimalUtil.sub(puSettlement.getKtotail().doubleValue(), puInvoice.getFpsl().doubleValue())));
            puSettlement.setDtotail(new BigDecimal(BigDecimalUtil.add(puSettlement.getDtotail().doubleValue(), puInvoice.getFpsl().doubleValue())));
            puSettlement.setIsInvoice(1);
            puSettlementMapper.updateById(puSettlement);
            if (puInvoice.getReceiptNumber() != null) {
                puInvoice.setYjjine(new BigDecimal(BigDecimalUtil.sub(puInvoice.getHsje().doubleValue(), puInvoice.getYfuseje().doubleValue())));
                puInvoice.setSupamount(puInvoice.getYfuseje());
                YxAdvancesReceived advancesReceived= updateAdvancesReceived(puInvoice);
                yxAdvancesReceivedMapper.updateById(advancesReceived);
                puInvoice.setYfsyje(new BigDecimal(BigDecimalUtil.sub(puInvoice.getYfsyje().doubleValue(), puInvoice.getYfuseje().doubleValue())));
                SoPayorder soPayorder = getSoPayOrder(puInvoice,precode);
                soPayorderMapper.insert(soPayorder);

            } else {
                puInvoice.setSupamount(new BigDecimal(0.000));
            }

            ////采购成本
            puInvoice.setXsFpsl(puInvoice.getFpsl());
            puInvoice.setTradecode(puSettlement.getTradecode()==null?null:puSettlement.getTradecode());
            puInvoiceMapper.insert(puInvoice);


            //采购成本
            List<WarehouseOrder> rkList = warehouseOrderMapper.getBypoNo(puInvoice.getPoOrder());//根据采购订单号查询所有入库单
            getChengBen(rkList);

            LoginUser user = sysBaseAPI.getUserById(puInvoice.getPoStaff());
            TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
            templateMessageDTO.setFromUser("管理员");
            templateMessageDTO.setToUser(puInvoice.getSaleman()+",");
            templateMessageDTO.setTitle(TITLE);
            templateMessageDTO.setTemplateCode("order");
            Map<String, String> templateParam = new HashMap<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date= simpleDateFormat.format(new Date());
            templateParam.put("ts_date",date);
            templateParam.put("ts_content", getMessage(user!=null?user.getRealname():"业务员不存在！", date));
            templateParam.put("checkOrder",puInvoice.getPuiNo());
            templateParam.put("cd_url","/puinvoice/puInvoice/list");
            templateMessageDTO.setTemplateParam(templateParam);
            sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);


            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }


    @Override
    public List<YxAdvancesReceived> getYfByPoOrder(String str){
        return puInvoiceMapper.getYfByPoOrder(str);
    }

    @Override
    @Transactional
    public boolean editInvoice(PuInvoice puInvoice,String precode) {
        try {
            PuInvoice invoice = puInvoiceMapper.getByNumber(puInvoice.getPuiNo());
            if(invoice.getReceiptNumber()!=null){
                YxAdvancesReceived advancesReceived =  addYf(invoice);
                yxAdvancesReceivedMapper.updateById(advancesReceived);
                SoPayorder soPayorder = soPayorderMapper.getByPuiNo(puInvoice.getPuiNo());
                soPayorderMapper.deleteById(soPayorder.getId());
            }
            if (puInvoice.getReceiptNumber() != null) {
                YxAdvancesReceived advancesReceived= updateAdvancesReceived(puInvoice);
                yxAdvancesReceivedMapper.updateById(advancesReceived);
                SoPayorder payorder = getSoPayOrder(puInvoice,precode);
                soPayorderMapper.insert(payorder);
            }else{
                puInvoice.setReceiptNumber(null);
                puInvoice.setYfuseje(null);
                puInvoice.setYfsyje(null);
            }
            //成本计算专用字段
            puInvoice.setXsFpsl(puInvoice.getFpsl());
            puInvoiceMapper.updateById(puInvoice);

            //采购成本
            List<WarehouseOrder> rkList = warehouseOrderMapper.getBypoNo(puInvoice.getPoOrder());//根据采购订单号查询所有入库单
            getChengBen(rkList);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    private YxAdvancesReceived addYf(PuInvoice puInvoice) throws Exception {
        YxAdvancesReceived advancesReceived = yxAdvancesReceivedMapper.getByReceiptNumber(puInvoice.getReceiptNumber());
        Double sup = advancesReceived.getSupAmount().doubleValue();
        Double amount = puInvoice.getYfuseje().doubleValue();
        advancesReceived.setSupAmount(new BigDecimal(BigDecimalUtil.add(sup, amount)));
        return advancesReceived;
    }


    @Override
    @Transactional
    public boolean deleteById(PuInvoice puInvoice) {
        try {
            List<WarehouseOrder> rkList = warehouseOrderMapper.getBypoNo(puInvoice.getPoOrder());//根据采购订单号查询所有入库单
            if (Integer.parseInt(puInvoice.getFplx()) != 4) {
                PuSettlement puSettlement = puSettlementMapper.getByPusNo(puInvoice.getPusNo());
                puSettlement.setKtotail(new BigDecimal(BigDecimalUtil.add(puSettlement.getKtotail().doubleValue(), puInvoice.getFpsl().doubleValue())));
                puSettlement.setDtotail(new BigDecimal(BigDecimalUtil.sub(puSettlement.getDtotail().doubleValue(), puInvoice.getFpsl().doubleValue())));
                List<PuInvoice> puInvoices = puInvoiceMapper.getByPusOrder(puInvoice.getPoOrder());
                puSettlement.setIsInvoice(puInvoices.isEmpty()?0:1);
                puSettlementMapper.updateById(puSettlement);
                puInvoiceMapper.deleteById(puInvoice.getId());
                if (puInvoice.getReceiptNumber() != null) {
                    YxAdvancesReceived advancesReceived =  addYf(puInvoice);
                    yxAdvancesReceivedMapper.updateById(advancesReceived);
                    SoPayorder soPayorder = soPayorderMapper.getByPuiNo(puInvoice.getPuiNo());
                    soPayorderMapper.deleteById(soPayorder.getId());
                }
            } else {
                PuBuyOrder puBuyOrder = puBuyOrderMapper.getByNumber(puInvoice.getPoOrder());
                if (puInvoice.getReceiptNumber() != null) {
                    YxAdvancesReceived advancesReceived =  addYf(puInvoice);
                    yxAdvancesReceivedMapper.updateById(advancesReceived);
                    SoPayorder soPayorder = soPayorderMapper.getByPuiNo(puInvoice.getPuiNo());
                    soPayorderMapper.deleteById(soPayorder.getId());
                }
                List<SoPayorder> soPayorders = soPayorderMapper.getListByPuiNo(puInvoice.getPuiNo());
                if (!soPayorders.isEmpty()) {
                    for (SoPayorder soPayorder : soPayorders) {
                        soPayorderMapper.deleteById(soPayorder.getId());
                    }
                }
                puBuyOrder.setYkje(new BigDecimal(BigDecimalUtil.sub(puBuyOrder.getYkje().doubleValue(), puInvoice.getHsje().doubleValue())));
                puBuyOrder.setYktotal(new BigDecimal(BigDecimalUtil.sub(puBuyOrder.getYktotal().doubleValue(), puInvoice.getFpsl().doubleValue())));
                puBuyOrder.setYhxTotail(puBuyOrder.getYktotal());
                puBuyOrder.setYhxMoney(puBuyOrder.getYkje());
                PuSettlement puSettlement = puSettlementMapper.getByPusNo(puInvoice.getPusNo());
                List<PuInvoice> invoices = puInvoiceMapper.getYkpByPoOrder(puInvoice.getPoOrder());
                if (invoices.size() == 1) {
                    puBuyOrder.setInvoice(0);
                }
                puSettlementMapper.deleteById(puSettlement.getId());
                puBuyOrderMapper.updateById(puBuyOrder);
                puInvoiceMapper.deleteById(puInvoice.getId());
            }
            //采购成本
            getChengBen(rkList);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    public void getChengBen(List<WarehouseOrder> rkList){
        List<SoOrderDetail> ckList = new ArrayList<>();
        if (rkList.size() > 0) {
            for (WarehouseOrder who : rkList) {
                //成本
                List<WarehouseOrderVo> ckNos = warehouseOrderVoMapper.getcknoByRkno(who.getWoNo());
                if (ckNos.size() > 0) {
                    for (WarehouseOrderVo ckNo : ckNos) {

                        SoOrderDetail sd = soOrderDetailMapper.getBySodNumber(ckNo.getSodNo());
                        if (sd != null) {
                            ckList.add(sd);
                            String sod = sd.getRkNo();
                            String[] sods = sod.split(",");
                            for (String sdd : sods) {
                                WarehouseOrder w = warehouseOrderMapper.getByWoNo(sdd);

                                //计算采购成本
//                    WarehouseOrder wh = warehouseOrderService.getById(wo.getWoNo());
                                List<PuInvoice> ykp = puInvoiceMapper.getYkpByPoOrder(w.getPoOrder());
                                List<PuInvoice> pt = puInvoiceMapper.getptfpByPoOrder(w.getPoOrder());

                                if (ykp.size() > 0) {
                                    for (PuInvoice s1 : ykp) {
                                        s1.setXsFpsl(s1.getFpsl());
                                        puInvoiceMapper.updateById(s1);
//                            ykp.add(s1);
                                    }
                                }
                                if (pt.size() > 0) {
                                    for (PuInvoice pi : pt) {
                                        pi.setXsFpsl(pi.getFpsl());
                                        puInvoiceMapper.updateById(pi);
                                    }
                                }

                            }

                        }
                    }
                }
            }

        }

        Collections.sort(ckList);
        if (ckList.size() > 0) {
            for (SoOrderDetail sd : ckList) {
                BigDecimal cb = BigDecimal.valueOf(0);
                BigDecimal cb2 = BigDecimal.valueOf(0);
//                    SoOrderDetail sd = soOrderDetailMapper.getBySodNumber(ck.getSodNo());
                String sork = sd.getRkNo();
                String[] srk = sork.split(",");
                for (String rk : srk) {
                    WarehouseOrder w = warehouseOrderMapper.getByWoNo(rk);
                    WarehouseOrderVo wh = warehouseOrderVoMapper.getByRknoAndCkno(rk, sd.getSodNo());

                    //计算采购成本
//                    WarehouseOrder wh = warehouseOrderService.getById(wo.getWoNo());
                    List<PuInvoice> fp = new ArrayList<>();
                    List<PuInvoice> ykp = puInvoiceMapper.getYkpByPoOrder(w.getPoOrder());//预开发票只能根据入库单的采购订单号查询
                    String no = w.getWoNo().substring(2, 4);
                    List<PuInvoice> ps = null;
                    if (!no.equals("RK")) {
                        ps = puInvoiceMapper.getBywoNo(w.getPuWoNo());
                    } else {
                        ps = puInvoiceMapper.getBywoNo(w.getWoNo());
                    }
                    if (ykp.size() > 0) {
                        for (PuInvoice p : ykp) {
                            fp.add(p);
                        }
                    }
                    if (ps.size() > 0) {
                        for (PuInvoice s1 : ps) {
                            fp.add(s1);
                        }
                    }
                    BigDecimal b = wh.getFyje();
                    BigDecimal s = BigDecimal.valueOf(0.00);
                    BigDecimal ss = BigDecimal.valueOf(0.00);
                    BigDecimal sd2 = BigDecimal.valueOf(0);
                    if (fp == null) {
                        ss = w.getWsdj().multiply(b);
                    } else {
                        for (PuInvoice pi : fp) {
                            if (b.compareTo(BigDecimal.valueOf(0.00)) == 1) {
                                //如果销售用开票数量<=出库单实际出库量
                                if (pi.getXsFpsl().compareTo(b) < 1) {
                                    s = s.add(pi.getWsdj().multiply(pi.getXsFpsl()));
                                    b = b.subtract(pi.getXsFpsl());
                                    pi.setXsFpsl(BigDecimal.valueOf(0.00));
                                    puInvoiceMapper.updateById(pi);
                                } else {
                                    s = s.add(pi.getWsdj().multiply(b));
                                    pi.setXsFpsl(pi.getXsFpsl().subtract(b));
                                    b = b.subtract(b);
                                    puInvoiceMapper.updateById(pi);
                                }
                            }
                        }
                        ss = s.add(b.multiply(w.getWsdj()));
                        sd2 = s.add(BigDecimal.valueOf(0));
                    }


                    cb = cb.add(ss);
                    cb2 = cb2.add(sd2);
                }
                sd.setCbJine(cb);
                sd.setCbJineTwo(cb2);
                Double jine = yxAdjustMapper.getJineByCkNo(sd.getSodNo());
                sd.setTzhJine(new BigDecimal(BigDecimalUtil.add(sd.getCbJine().doubleValue(),jine)));
                soOrderDetailMapper.updateById(sd);
            }
        }
    }


}
